package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName IndexController
 * @Author bsy
 * @Description TODO
 * @Date 2021/12/28 23:34
 * @Version 1.0
 */
@RestController
public class IndexController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    int i = 1;
    @RequestMapping("/noLock/reduceStock")
    public String reduceStock() {
        String msg = "";
        //用redis模拟数据库
        int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
        if (stock > 0) {
            int realStock = stock - 1;
            redisTemplate.opsForValue().set("stock", realStock + "");
            msg = "当前客户:" + (i++) + " 购买成功，剩余:" + realStock;
            System.out.println(msg);
        } else {
            msg = "购买失败，库存不足";
            System.out.println(msg);
        }
        return msg;
    }

}
